//
//  GXButton.swift
//  GameCatchBall
//
//  Created by GuangXiao on 16/1/19.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class GXButton: UIButton {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    private func setupUI(){
        var image = clipImage()
        image = image.imageWithRenderingMode(.AlwaysOriginal)
        setImage(image, forState: .Normal)
        setImage(image,forState: .Highlighted)
        sizeToFit()
    }
    //截取圆形图片的方法
    private func clipImage()->UIImage{
        let image = UIImage(named: "\(arc4random()%6 + 1)")
        
        //        // 2.开启图片类型的图形上下文

        UIGraphicsBeginImageContextWithOptions(image!.size, false, 0)
        //        // 7.获取当前上下文
        let ctx = UIGraphicsGetCurrentContext()
        //        // 6.画显示的区域
        CGContextAddArc(ctx, image!.size.width * 0.5, image!.size.height * 0.5, image!.size.width * 0.5, 0, CGFloat(2 * M_PI), 1)

        //        // 8.裁剪
        CGContextClip(ctx)

        //        // 4.先把图片 画到 图片类型的上下文当中
        image?.drawAtPoint(CGPointZero)
        
        //        // 5.取图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        //        // 3.关闭图片类型的图形上下文
        UIGraphicsEndImageContext()
        
        return newImage
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
